package com.cyanite.playlv2;

import com.cyanite.playlv2.util.NotificationsUtil;
import com.cyanite.playlv2api.types.Info;
import com.cyanite.playlv2api.types.Response;
import com.cyanite.playlv2api.types.Task;
import com.cyanite.playlv2api.types.TaskCategory;
import com.cyanite.playlv2api.util.ConstantsUtils;
import com.cyanite.playlv2api.util.ConstantsUtils.ShareSecretLevelConsts;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class ShareShoutWithPhotoActivity extends Activity {

    public static final String EXTRA_TASK_CATEGORY_PARCEL = PlayLv2.PACKAGE_NAME
        + ".ShareShoutWithPhotoActivity.EXTRA_TASK_CATEGORY_PARCEL";

    private ImageView mImg;
    private ProgressDialog mProgressDialog;
    private StateHolder mStateHolder;
    private EditText mInfo;

    private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerReceiver(mLoggedOutReceiver, new IntentFilter(PlayLv2.INTENT_ACTION_LOGGED_OUT));

        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, 0);
        setContentView( R.layout.share_shout_with_photo_activity );

        mStateHolder = new StateHolder();
        if (getIntent().hasExtra(EXTRA_TASK_CATEGORY_PARCEL))  {
            mStateHolder.setTaskCategory((TaskCategory)getIntent().getExtras().getParcelable(EXTRA_TASK_CATEGORY_PARCEL));
        }   else {
            finish();
            return;
        }

        mInfo = (EditText)findViewById(R.id.etCommonInfo);
        mImg = (ImageView)findViewById(R.id.imgUserPhoto);
        Button btnCreate = (Button)findViewById(R.id.btnPublishShoutWithPhoto);
        btnCreate.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                if (!TextUtils.isEmpty(mInfo.getText().toString())) {
                    Info info = new Info();
                    info.setInfo1(mInfo.getText().toString());
                    mStateHolder.startTaskSharePhoto(ShareShoutWithPhotoActivity.this, info);
                } else {
                    Toast.makeText(ShareShoutWithPhotoActivity.this,
                            getResources().getString(R.string.share_info_content_null),
                            Toast.LENGTH_LONG).show();
                }
             }
         });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data.getAction() == null && resultCode == 0 ){
            finish();
        }else{
            Bundle extras = data.getExtras();
            Bitmap bmp = (Bitmap) extras.get("data");
            mImg.setImageBitmap(bmp);
            TaskSetPhoto mTaskSetPhoto = new TaskSetPhoto(this, bmp);
            mTaskSetPhoto.execute();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (isFinishing()) {
            mStateHolder.cancelTasks();
            unregisterReceiver(mLoggedOutReceiver);
        }
    }

    private ProgressDialog showProgressDialog(int res) {
        if (mProgressDialog == null) {
            ProgressDialog dialog = new ProgressDialog(this);
            dialog.setIndeterminate(true);
            dialog.setCancelable(true);
            mProgressDialog = dialog;
        }
        mProgressDialog.setMessage(getString(res));
        mProgressDialog.show();
        return mProgressDialog;
    }

    private void dismissProgressDialog() {
        try {
            mProgressDialog.dismiss();
        } catch (IllegalArgumentException e) {
            // We don't mind. android cleared it for us.
        }
    }

    private void onTaskSetPhotoComplete(Response response, Exception ex) {
        dismissProgressDialog();
        if (response != null) {
            mStateHolder.setPhotoId(response.getValue());
        } else {
            NotificationsUtil.ToastReasonForFailure(this, ex);
        }
    }

    private static class TaskSetPhoto extends AsyncTask<Void, Void, Response> {

        private ShareShoutWithPhotoActivity mActivity;
        private Exception mReason;
        private Bitmap mBmp;

        public TaskSetPhoto(ShareShoutWithPhotoActivity activity, Bitmap bmp) {
            mActivity = activity;
            mBmp = bmp;
        }

        @Override
        protected void onPreExecute() {
            mActivity.showProgressDialog(R.string.share_info_bitmap_progress_note);
        }

        @Override
        protected Response doInBackground(Void... params) {
            try {
                return ((PlayLv2) mActivity.getApplication()).getPlayLv2Api().photoUpdate2(mBmp);
            } catch (Exception ex) {
                mReason = ex;
                return null;
            }
        }

        @Override
        protected void onPostExecute(Response response) {
            if (mActivity != null) {
                mActivity.onTaskSetPhotoComplete(response, mReason);
            }
        }

        @Override
        protected void onCancelled() {
            mActivity.dismissProgressDialog();
        }
    }

    private void onSharePhotoTaskComplete(Response response, Exception ex) {
        dismissProgressDialog();
        if (response != null && response.getValue().equals("0")) {
            Toast.makeText(ShareShoutWithPhotoActivity.this,
                    getResources().getString(R.string.share_info_ok),
                    Toast.LENGTH_LONG).show();
            finish();
        } else {
            NotificationsUtil.ToastReasonForFailure(this, ex);
        }
    }

    private static class SharePhotoTask extends AsyncTask<Void, Void, Response> {

        private ShareShoutWithPhotoActivity mActivity;
        private Exception mReason;
        private Task mTask;

        public SharePhotoTask(ShareShoutWithPhotoActivity activity, Task task) {
            mActivity = activity;
            mTask = task;
        }

        @Override
        protected void onPreExecute() {
            mActivity.showProgressDialog(R.string.share_info_progress_note);
        }

        @Override
        protected Response doInBackground(Void... params) {
            String validateGps = "1";
            Location loc = ((PlayLv2)mActivity.getApplication()).getLastKnownLocation();
            if (loc == null) {
                try {
                    Thread.sleep(ConstantsUtils.SLEEP_TIME_IF_NO_LOCATION);
                    } catch (InterruptedException ex) {}
                loc = ((PlayLv2)mActivity.getApplication()).getLastKnownLocation();
            }
            if (loc != null)    {
                mTask.setLatitude(String.valueOf(loc.getLatitude()));
                mTask.setLongitude(String.valueOf(loc.getLongitude()));
            }   else {
                validateGps = "2";
            }
            //
            try {
                Response response = null;
                response = ((PlayLv2) mActivity.getApplication()).getPlayLv2Api().share(mTask, validateGps);
                if (response == null) response = new Response();
                return response;
            } catch (Exception ex) {
                mReason = ex;
                return null;
            }
        }

        @Override
        protected void onPostExecute(Response response) {
            if (mActivity != null) {
                mActivity.onSharePhotoTaskComplete(response, mReason);
            }
        }

        @Override
        protected void onCancelled() {
            mActivity.dismissProgressDialog();
        }
    }

    private static class StateHolder {

        private SharePhotoTask mTaskSharePhoto;
        private TaskCategory mTaskCategory;
        private String mPhotoId;

        public StateHolder() {
            mPhotoId = "";
        }

        public void setPhotoId(String id) {
            mPhotoId = id;
        }

        public void setTaskCategory(TaskCategory taskcat) {
            mTaskCategory = taskcat;
        }

        public void startTaskSharePhoto(ShareShoutWithPhotoActivity activity, Info info) {
            Task task = new Task();
            task.setPhotoId(mPhotoId);
            task.setTaskCategoryId(mTaskCategory.getId());
            task.setInfo(info);
            task.setSecretLevel(ShareSecretLevelConsts.SHARE_SECRET_LEVEL_OPEN);

            mTaskSharePhoto = new SharePhotoTask(activity, task);
            mTaskSharePhoto.execute();
        }

        public void cancelTasks() {
            if (mTaskSharePhoto != null) {
                mTaskSharePhoto.cancel(true);
            }
        }
    }
}
